import React, { useEffect, useState } from 'react'
import { Redirect, Route, Switch } from 'react-router-dom'
import Home from '../../views/sandbox/home/Home'
import NoPermission from '../../views/sandbox/nopermission/NoPermission'
import RightList from '../../views/sandbox/right-manage/RightList'
import RoleList from '../../views/sandbox/right-manage/RoleList'
import UserList from '../../views/sandbox/user-manage/UserList'
import NewsAdd from '../../views/sandbox/news-manage/NewsAdd'
import NewsDraft from '../../views/sandbox/news-manage/NewsDraft'
import NewsCategory from '../../views/sandbox/news-manage/NewsCategory'
import NewsPreview from '../../views/sandbox/news-manage/NewsPreview'
import NewsUpdate from '../../views/sandbox/news-manage/NewsUpdate'
import Audit from '../../views/sandbox/audit-manage/Audit'
import AuditList from '../../views/sandbox/audit-manage/AuditList'
import Unpublished from '../../views/sandbox/publish-manage/Unpublished'
import Published from '../../views/sandbox/publish-manage/Published'
import Sunset from '../../views/sandbox/publish-manage/Sunset'
import { rightsChildren } from '../../api/api'

const LocalRouterMap={
    "/home":Home,
    "/user-manage/list":UserList,
    "/right-manage/role/list":RoleList,
    "/right-manage/right/list":RightList,
    "/news-manage/add": NewsAdd,
    "/news-manage/draft":NewsDraft,
    "/news-manage/category":NewsCategory,
    "/news-manage/preview/:id":NewsPreview,
    "/news-manage/update/:id":NewsUpdate,
    "/audit-manage/audit":Audit,
    "/audit-manage/list":AuditList,
    "/publish-manage/unpublished":Unpublished,
    "/publish-manage/published":Published,
    "/publish-manage/sunset":Sunset,
}

export default function NewRoute() {
    const [backRouteList,setBackRouteList]=useState([])
    useEffect(()=>{
        const httpRequest = async () => {
            //获取后台菜单router
            const res=await rightsChildren()
            setBackRouteList(res.data.data);
          }
          httpRequest()
    },[])

    const {role:{rights}}=JSON.parse(localStorage.getItem("token"))
    const checkRoute=(item)=>{
        return LocalRouterMap[item.key] && (item.pagepermisson || item.routepermisson)
    }
    const checkUserPerission=(item)=>{
        return rights.includes(item.key)
    }
    return (
        <Switch>
            {backRouteList.map(item=>{
                if(checkRoute(item) && checkUserPerission(item)){
                    return <Route path={item.key} component={LocalRouterMap[item.key]} key={item.key} exact/>
                }
                return null
            })}
            <Redirect from="/" to="/home" exact></Redirect>
            {
                backRouteList.length>0 && <Route path="*" component={NoPermission} />
            }
            
        </Switch>
    )
}
